
function setCookie(key, value, timing) {
    var date = new Date();
    date.setDate(date.getDate() + timing);
    document.cookie = key + "=" + value + ";expires=" + date;
}

function getCookie(key) {
    var arr = document.cookie.split("; ");
    for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split("=");
        if (key === arr2[0]) {
            return arr2[1]
        }
    }
}
function removeCookie(key) {
    setCookie(key, "", -1);
}
//添加商品进购物车
var add = document.querySelector(".add");
var _itemName = document.querySelector(".goods-name");
var _itemPrice = document.querySelector(".goods-price");
add.onclick = function () {
   
    //    先取转换成数组
    var carts = getCookie('carts') ? JSON.parse(getCookie('carts')) : [];
    var item = {
        itemName: _itemName.innerHTML,
        itemPrice: parseFloat(_itemPrice.innerHTML),
        itemNum: 1,
        isChecked: true
    }
    //   判断有没有重复
    var res = carts.some(function (el) {
        return el.itemName === item.itemName
    })
    console.log(res)
    if (res) {
        alert('购物车中已经有该商品，请勿重复添加');
        return;
    }
    else{
        alert("已添加进购物车")
    }
    carts.unshift(item);
    setCookie("carts", JSON.stringify(carts),5)
}


$(function(){
    spanWH();
 $(".leftView").on("mouseover",function(){
     $('.rightView').css('display','block');
     $('.glass').css('display','block');
 });
 $(".leftView").on("mouseout",function(){
     $(".rightView").css("display","none");
     $(".glass").css("display","none");
 });
 $('.leftView').on('mousemove',function(eve){
  var e=eve ||event;
  //span的移动距离
  var spanL=e.pageX-$(this).offset().left-$(".glass").width()/2;
  var spanT=e.pageY-$(this).offset().top-$(".glass").height()/2;
  //设置边界
  if(spanL<0){
      spanL=0;
  };
  if(spanT<0){
 spanT=0;
  };
  if(spanL>$(this).width()-$(".glass").width()){
      spanL=$(this).width()-$(".glass").width();
  }
  if(spanT>$(this).height()-$(".glass").height()){
     spanT=$(this).height()-$(".glass").height();
  }
  //右边大图的移动距离
var  bigImgL=spanL*($(".rightView img").width()-$(".rightView").width()) / ($(".leftView").width()-$(".glass").width());
var  bigImgT=spanT*($(".rightView img").height()-$(".rightView").height()) / ($(".leftView").height()-$(".glass").height());
$(".glass").css({
     "left":spanL,
     "top":spanT,
  });
  $(".rightView img").css({
      "left":-bigImgL,
      "top":-bigImgT,
  });
 })
 
 // 设置span宽和高
     function spanWH(){
         var spanW=$(".leftView").width() / $(".rightView img").width() * $(".leftView").width()/2;
         var spanH=$(".leftView").height() / $(".rightView img").height() * $(".leftView").height()/2;
     $(".glass").css({
         "width":spanW,
         "height":spanH,
     });
     };
 })